package com.example.servlet;

import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/book-detail")
public class BookDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookIdStr = request.getParameter("bookId");
        int bookId = -1;
        try {
            if (bookIdStr == null || bookIdStr.trim().isEmpty()) {
                response.sendRedirect("/books");
                return;
            }
            bookId = Integer.parseInt(bookIdStr);
        } catch (NumberFormatException e) {
            response.sendRedirect("/books");
            return;
        }
        Map<String, Object> book = new HashMap<>();
        String sql = "SELECT * FROM books WHERE id = ?";
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, bookId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                book.put("id", rs.getInt("id"));
                book.put("name", rs.getString("name"));
                book.put("author", rs.getString("author"));
                book.put("cover_url", rs.getString("cover_url"));
                book.put("description", rs.getString("description"));
                book.put("catalog", rs.getString("catalog"));
                book.put("category", rs.getString("category"));
                book.put("publisher", rs.getString("publisher"));
                book.put("price", rs.getBigDecimal("price"));
                book.put("stock", rs.getInt("stock"));
                book.put("sales", rs.getInt("sales"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 查询图书评论（假设有book_comment表，字段：id, book_id, user, content, create_time）
        List<Map<String, Object>> comments = new ArrayList<>();
        String commentSql = "SELECT user, content FROM book_comment WHERE book_id = ? ORDER BY create_time DESC LIMIT 5";
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(commentSql)) {
            ps.setInt(1, bookId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Map<String, Object> c = new HashMap<>();
                c.put("user", rs.getString("user"));
                c.put("content", rs.getString("content"));
                comments.add(c);
            }
        } catch (Exception e) {
            // 没有评论表时可忽略
        }
        book.put("comments", comments);
        request.setAttribute("book", book);
        request.getRequestDispatcher("/book-detail.jsp").forward(request, response);
    }
} 